import requests
from requests.exceptions import RequestException
from config.config import BASE_URL, TOKEN, TIMEOUT
# from core.logger import logger
from core import log
from core.retry import retry_request


class APIClient:

    def __init__(self, base_url=BASE_URL, token=TOKEN):
        self.base_url = base_url
        self.session = requests.Session()
        self.session.headers.update({
            "Content-Type": "application/json",
            "User-Agent": "API-Automation/1.0",
        })
        if token:
            self.session.headers.update({"Authorization": f"Bearer {token}"})

    @retry_request  # 自带重试机制
    def request(self, method, path, **kwargs):
        logger = log.Log.get_logger()
        # path may already include leading slash
        url = f"{self.base_url}{path}"
        try:
            resp = self.session.request(method, url, timeout=TIMEOUT, **kwargs)
            resp.raise_for_status()
            logger.info(f"{method} {url} -> {resp.status_code}")
            return resp
        except RequestException as e:
            # include response text when available to help debugging
            if hasattr(e, 'response') and e.response is not None:
                logger.error(f"请求失败: {e} | resp_text={e.response.text[:500]}")
            else:
                logger.error(f"请求失败: {e}")
            raise
